package com.stoneframe.base.dao;

import java.util.List;

import javax.annotation.Resource;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;

public abstract class DaoSupport implements IDao {
	
	protected abstract SqlSessionTemplate getSqlSessionTemplate();
	
	/**
	 * 保存对象
	 */
	public Object save(String str, Object obj) throws Exception {
		// TODO Auto-generated method stub
		return getSqlSessionTemplate().insert(str,obj);
	}
	
	/**
	 * 批量保存
	 */
	public Object save(String str,List objs) throws Exception{
		return getSqlSessionTemplate().insert(str,objs);
	}

	/**
	 * 修改对象
	 */
	public Object edit(String str, Object obj) throws Exception {
		// TODO Auto-generated method stub
		return getSqlSessionTemplate().update(str,obj);
	}
	
	/**
	 * 批量修改
	 */
	public void edit(String str,List objs) throws Exception{
		SqlSessionFactory sqlSessionFactory=getSqlSessionTemplate().getSqlSessionFactory();
		//批量执行器
		SqlSession sqlSession=sqlSessionFactory.openSession(ExecutorType.BATCH,false);
		try{
			if(objs!=null){
				for(int i=0,size=objs.size();i<size;i++){
					sqlSession.update(str, objs.get(i));
				}
				sqlSession.flushStatements();
				sqlSession.commit();
				sqlSession.clearCache();
			}
		}finally{
			sqlSession.close();
		}
	}

	/**
	 * 删除对象 
	 */
	public Object del(String str, Object obj) throws Exception {
		// TODO Auto-generated method stub
		return getSqlSessionTemplate().delete(str,obj);
	}
	
	/**
	 * 批量删除
	 */
	public Object del(String str,List objs) throws Exception{
		return getSqlSessionTemplate().delete(str, objs);
	}

	/**
	 * 查找对象
	 */
	public Object findForObject(String str, Object obj) throws Exception {
		// TODO Auto-generated method stub
		return getSqlSessionTemplate().selectOne(str,obj);
	}

	/**
	 * 查找对象
	 */
	public Object findForList(String str, Object obj) throws Exception {
		// TODO Auto-generated method stub
		return getSqlSessionTemplate().selectList(str,obj);
	}

	/**
	 * 查找对象封装成Map
	 */
	public Object findForMap(String sql, Object obj, String key, String value)
			throws Exception {
		// TODO Auto-generated method stub
		return getSqlSessionTemplate().selectMap(sql, obj, key);
	}

}
